﻿using DevExpress.XtraEditors;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using AdbService;

namespace XChipTool
{
    public partial class ADBForm : DevExpress.XtraEditors.XtraForm
    {
        private ProcessStartInfo logInfo;
        private BackgroundWorker pingWorker;
        private CancellationTokenSource tokenSource;
        private Process currentLogProcess;
        private string workingDirectory = $"{AppDomain.CurrentDomain.BaseDirectory}adb";

        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;

        // 日志文件路径
        private string logFilePath => Path.Combine(workingDirectory, "adb_log.txt");
        private string cmdFilePath => Path.Combine(workingDirectory, "cmd_log.txt");

        public ADBForm()
        {
            InitializeComponent();
            InitializeProcessInfo();
            RegisterAdbServiceEvents();
            InitializeUI();
            //RestartAdbServer();
        }

        /// <summary>
        /// 初始化UI
        /// </summary>
        private void InitializeUI()
        {
            // 设置文本框为只读和多行
            comTxt.Properties.ReadOnly = true;
            logTxt.Properties.ReadOnly = true;

            comTxt.Properties.Appearance.BackColor = Color.Black;
            comTxt.Properties.Appearance.ForeColor = Color.Lime;
            comTxt.Properties.Appearance.Font = new Font("Consolas", 9);

            logTxt.Properties.Appearance.BackColor = Color.Black;
            logTxt.Properties.Appearance.ForeColor = Color.Cyan;
            logTxt.Properties.Appearance.Font = new Font("Consolas", 9);

            // 添加状态标签
            UpdateStatus("ADB工具已就绪");
        }

        /// <summary>
        /// 更新状态栏
        /// </summary>
        private void UpdateStatus(string message)
        {
            if (statusLabel.InvokeRequired)
            {
                statusLabel.Invoke(new Action<string>(UpdateStatus), message);
            }
            else
            {
                statusLabel.Text = $"[{DateTime.Now:HH:mm:ss}] {message}";
            }
        }

        /// <summary>
        /// 注册ADB服务事件
        /// </summary>
        private void RegisterAdbServiceEvents()
        {
            adbService.CommandExecuted += OnAdbCommandExecuted;
            adbService.CommandError += OnAdbCommandError;
        }

        /// <summary>
        /// 取消注册ADB服务事件
        /// </summary>
        private void UnregisterAdbServiceEvents()
        {
            adbService.CommandExecuted -= OnAdbCommandExecuted;
            adbService.CommandError -= OnAdbCommandError;
        }

        /// <summary>
        /// ADB命令执行完成事件处理
        /// </summary>
        private void OnAdbCommandExecuted(object sender, AdbCommandEventArgs e)
        {
            SafeUpdateTextBox(comTxt, e.Result);
            WriteToCmdFile(e.Result);
            WriteToLogFile($"[COMMAND] {e.OperationName}: {e.Command}");
            WriteToLogFile($"[RESULT] {e.Result}");
            UpdateStatus($"{e.OperationName} 执行完成");
        }

        /// <summary>
        /// ADB命令执行错误事件处理
        /// </summary>
        private void OnAdbCommandError(object sender, AdbCommandEventArgs e)
        {
            SafeUpdateTextBox(comTxt, e.Result);
            WriteToLogFile($"[ERROR] {e.OperationName}: {e.Command}");
            WriteToLogFile($"[ERROR_DETAIL] {e.Result}");
            UpdateStatus($"{e.OperationName} 执行失败");
        }

        /// <summary>
        /// 构建ADB命令（根据是否指定设备序列号）
        /// </summary>
        private string BuildAdbCommand(string baseCommand)
        {
            if (!string.IsNullOrEmpty(devicestxt.Text))
            {
                // 在adb后插入-s参数
                return baseCommand.Replace("adb ", $"adb -s {devicestxt.Text} ");
            }
            return baseCommand;
        }

        private void InitializeProcessInfo()
        {
            logInfo = ProcessStartInfoManager.GetDefaultCmdStartInfo();
        }

        /// <summary>
        /// 在UI线程安全地更新文本框
        /// </summary>
        private void SafeUpdateTextBox(TextEdit textBox, string text)
        {
            if (textBox.InvokeRequired)
            {
                textBox.Invoke(new Action<TextEdit, string>(SafeUpdateTextBox), textBox, text);
            }
            else
            {
                // 限制文本框内容长度，避免内存问题
                if (textBox.Text.Length > 10000)
                {
                    textBox.Text = textBox.Text.Substring(textBox.Text.Length - 5000);
                }

                textBox.Text += $"[{DateTime.Now:HH:mm:ss}] {text}{Environment.NewLine}";
                textBox.SelectionStart = textBox.Text.Length;
                textBox.ScrollToCaret();
            }
        }

        /// <summary>
        /// 写入日志文件
        /// </summary>
        private void WriteToLogFile(string logMessage)
        {
            try
            {
                File.AppendAllText(logFilePath, $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {logMessage}{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"写入日志文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 写入cmd日志文件
        /// </summary>
        private void WriteToCmdFile(string logMessage)
        {
            try
            {
                File.AppendAllText(cmdFilePath, $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {logMessage}{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"写入日志文件失败: {ex.Message}");
            }
        }

        #region 按钮点击事件处理

        private void rootBtn_Click(object sender, EventArgs e)
        {
            UpdateStatus("正在获取Root权限...");
            string command = BuildAdbCommand("adb root");
            adbService.ExecuteAdbCommand(command, "ADB Root");
        }

        private void debugBtn_Click(object sender, EventArgs e)
        {
            UpdateStatus("正在启用调试模式...");
            string command = BuildAdbCommand("adb shell setprop vendor.extcamera.xxw.ispdebug 1");
            adbService.ExecuteAdbCommand(command, "启用调试模式");
        }

        private async void startBtn_Click(object sender, EventArgs e)
        {
            try
            {
                // 检查是否已经在运行
                if (IsLogMonitorRunning())
                {
                    SafeUpdateTextBox(comTxt, "日志监控已经在运行中");
                    UpdateStatus("日志监控运行中");
                    return;
                }

                UpdateStatus("正在启动日志监控...");

                // 先停止日志监控（如果正在运行）
                await StopLogMonitorAsync();

                // 额外等待确保完全停止
                await Task.Delay(300);

                // 检查并确保BackgroundWorker可用
                if (pingWorker == null || pingWorker.IsBusy)
                {
                    SafeUpdateTextBox(comTxt, "工作线程状态异常，正在重新初始化...");
                    pingWorker?.Dispose();
                    InitializeBackgroundWorker();
                    await Task.Delay(200);
                }

                // 再次检查
                if (pingWorker.IsBusy)
                {
                    SafeUpdateTextBox(comTxt, "日志监控启动失败: 工作线程仍忙，请稍后重试");
                    UpdateStatus("启动失败 - 工作线程忙");
                    return;
                }

                // 启用调试模式
                string debugCommand = BuildAdbCommand("adb shell setprop vendor.extcamera.xxw.ispdebug 1");
                adbService.ExecuteAdbCommand(debugCommand, "启用调试模式");

                // 清空日志缓存
                ClearLogcatBuffer();

                // 重新初始化 CancellationTokenSource
                tokenSource?.Dispose();
                tokenSource = new CancellationTokenSource();

                // 启动新的日志监控
                pingWorker.RunWorkerAsync(tokenSource.Token);

                SafeUpdateTextBox(comTxt, "日志监控已启动");
                UpdateStatus("日志监控运行中");
            }
            catch (Exception ex)
            {
                SafeUpdateTextBox(comTxt, $"启动日志监控失败: {ex.Message}");
                UpdateStatus("日志监控启动失败");

                // 启动失败时强制清理
                ForceCleanup();
            }
        }

        /// <summary>
        /// 改进的停止日志监控方法
        /// </summary>
        private async Task StopLogMonitorAsync()
        {
            try
            {
                tokenSource?.Cancel();

                lock (_processLock)
                {
                    _isLogMonitorRunning = false;

                    // 安全停止进程
                    if (_logMonitorProcess != null)
                    {
                        SafeStopProcess(_logMonitorProcess);
                        _logMonitorProcess = null;
                    }
                }

                // 等待 BackgroundWorker 停止
                if (pingWorker != null && pingWorker.IsBusy)
                {
                    pingWorker.CancelAsync();

                    int waitCount = 0;
                    while (pingWorker.IsBusy && waitCount < 30)
                    {
                        await Task.Delay(100);
                        waitCount++;
                    }

                    // 如果仍然在运行，强制重新初始化
                    if (pingWorker.IsBusy)
                    {
                        pingWorker.Dispose();
                        InitializeBackgroundWorker();
                    }
                }

                SafeUpdateTextBox(comTxt, "日志监控已停止");
                UpdateStatus("日志监控已停止");
            }
            catch (Exception ex)
            {
                SafeUpdateTextBox(comTxt, $"停止日志监控时出错: {ex.Message}");
                UpdateStatus("停止监控时出错");

                // 强制清理
                ForceCleanup();
            }
        }
        /// <summary>
        /// 强制清理资源
        /// </summary>
        private void ForceCleanup()
        {
            lock (_processLock)
            {
                try
                {
                    _isLogMonitorRunning = false;

                    if (_logMonitorProcess != null)
                    {
                        if (!_logMonitorProcess.HasExited)
                        {
                            _logMonitorProcess.Kill();
                            _logMonitorProcess.WaitForExit(1000);
                        }
                        _logMonitorProcess.Dispose();
                        _logMonitorProcess = null;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"强制清理失败: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 检查日志监控状态
        /// </summary>
        private bool IsLogMonitorRunning()
        {
            lock (_processLock)
            {
                return _isLogMonitorRunning &&
                       _logMonitorProcess != null &&
                       !_logMonitorProcess.HasExited;
            }
        }


        private async void endBtn_Click(object sender, EventArgs e)
        {
            await StopLogMonitorAsync();
        }

        private async void readBtn_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(addrtxt.Text))
            {
                MessageBox.Show("请输入地址值", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string address = addrtxt.Text.Trim();
            string baseCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
            string adbCommand = BuildAdbCommand(baseCommand);

            UpdateStatus($"读取地址: {address}");
            await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

            // 异步等待寄存器值
            await WaitForRegisterValueAsync(address);
        }

        /// <summary>
        /// 异步等待寄存器值
        /// </summary>
        private async Task WaitForRegisterValueAsync(string address)
        {
            try
            {
                UpdateStatus($"正在等待寄存器 {address} 的响应...");

                // 使用异步方式等待寄存器值
                var records = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 2000));

                // 更新UI显示结果
                if (valtxt.InvokeRequired)
                {
                    valtxt.Invoke(new Action<string>(s =>
                    {
                        valtxt.Text = s;
                        if (s == "0")
                        {
                            UpdateStatus($"读取完成: {address} = {s} (默认值)");
                        }
                        else
                        {
                            UpdateStatus($"读取成功: {address} = {s}");
                        }
                    }), records.Values);
                }
                else
                {
                    valtxt.Text = records.Values;
                    if (records.Values == "0")
                    {
                        UpdateStatus($"读取完成: {address} = {records.Values} (默认值)");
                    }
                    else
                    {
                        UpdateStatus($"读取成功: {address} = {records.Values}");
                    }
                }

                Console.WriteLine($"[AdbDeviceManager] 读取寄存器完成: {address} = {records.Values}");
            }
            catch (Exception ex)
            {
                UpdateStatus($"读取失败: {ex.Message}");
                // 可以选择在UI线程显示错误消息
                if (MessageBox.Show($"读取寄存器时发生错误: {ex.Message}\n是否重试?", "错误",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                {
                    // 重试读取
                    await WaitForRegisterValueAsync(address);
                }
            }
        }

        private void witeBtn_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(addrtxt.Text) || string.IsNullOrEmpty(valtxt.Text))
            {
                MessageBox.Show("请输入地址和值", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string address = addrtxt.Text.Trim();
            string value = valtxt.Text.Trim();
            string baseCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{value},0\"";
            string adbCommand = BuildAdbCommand(baseCommand);

            UpdateStatus($"写入地址:{address} 值:{value}");
            adbService.ExecuteAdbCommand(adbCommand, $"写操作 - 地址:{address} 值:{value}");
        }

        private void clearComBtn_Click(object sender, EventArgs e)
        {
            comTxt.Text = "";
            UpdateStatus("命令输出已清空");
        }

        private void clearLogBtn_Click(object sender, EventArgs e)
        {
            logTxt.Text = "";
            UpdateStatus("日志输出已清空");
        }

        private void saveLogBtn_Click(object sender, EventArgs e)
        {
            try
            {
                using (SaveFileDialog saveDialog = new SaveFileDialog())
                {
                    saveDialog.Filter = "文本文件|*.txt|所有文件|*.*";
                    saveDialog.Title = "保存日志文件";
                    saveDialog.FileName = $"adb_log_{DateTime.Now:yyyyMMdd_HHmmss}.txt";

                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        string content = $"=== 命令输出 ==={Environment.NewLine}{comTxt.Text}{Environment.NewLine}" +
                                       $"=== 日志输出 ==={Environment.NewLine}{logTxt.Text}";

                        File.WriteAllText(saveDialog.FileName, content);
                        UpdateStatus($"日志已保存到: {saveDialog.FileName}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存日志失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region 后台工作线程

        private void ADBForm_Load(object sender, EventArgs e)
        {
            InitializeBackgroundWorker();
            CheckAdbEnvironment();
        }

        /// <summary>
        /// 检查ADB环境
        /// </summary>
        private void CheckAdbEnvironment()
        {
            try
            {
                if (!Directory.Exists(workingDirectory))
                {
                    SafeUpdateTextBox(comTxt, $"警告: ADB目录不存在: {workingDirectory}");
                    UpdateStatus("ADB目录不存在");
                    return;
                }

                // 检查adb可执行文件
                string adbExePath = Path.Combine(workingDirectory, "adb.exe");
                if (!File.Exists(adbExePath))
                {
                    SafeUpdateTextBox(comTxt, $"警告: 未找到adb.exe: {adbExePath}");
                    UpdateStatus("ADB工具缺失");
                    return;
                }

                SafeUpdateTextBox(comTxt, "ADB环境检查通过");
                UpdateStatus("ADB环境正常");
            }
            catch (Exception ex)
            {
                SafeUpdateTextBox(comTxt, $"环境检查失败: {ex.Message}");
                UpdateStatus("环境检查失败");
            }
        }

        private void InitializeBackgroundWorker()
        {
            pingWorker = new BackgroundWorker
            {
                WorkerSupportsCancellation = true
            };
            pingWorker.DoWork += PingWorker_DoWork;
            pingWorker.RunWorkerCompleted += PingWorker_RunWorkerCompleted;
        }

        // 在类级别添加进程管理相关的字段
        private Process _logMonitorProcess;
        private bool _isLogMonitorRunning = false;
        private readonly object _processLock = new object();


        private void PingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (!(e.Argument is CancellationToken token))
                return;

            BackgroundWorker worker = sender as BackgroundWorker;

            try
            {
                WriteToLogFile("开始日志监控");

                // 在启动监控前先执行独立的清空命令
                ClearLogcatBuffer();

                lock (_processLock)
                {
                    // 如果进程已经存在，先停止它
                    if (_logMonitorProcess != null && !_logMonitorProcess.HasExited)
                    {
                        SafeStopProcess(_logMonitorProcess);
                        _logMonitorProcess = null;
                    }

                    // 创建新的进程实例
                    _logMonitorProcess = new Process();
                    _logMonitorProcess.StartInfo = logInfo;
                    _logMonitorProcess.StartInfo.RedirectStandardInput = true;
                    _logMonitorProcess.StartInfo.RedirectStandardOutput = true;
                    _logMonitorProcess.StartInfo.UseShellExecute = false;
                    _logMonitorProcess.StartInfo.CreateNoWindow = true;
                    _logMonitorProcess.StartInfo.WorkingDirectory = workingDirectory;
                    _logMonitorProcess.EnableRaisingEvents = true; // 启用进程退出事件

                    // 注册进程退出事件
                    _logMonitorProcess.Exited += (s, args) =>
                    {
                        _isLogMonitorRunning = false;
                        WriteToLogFile("日志监控进程已退出");
                    };

                    _logMonitorProcess.Start();
                    _isLogMonitorRunning = true;
                }

                // 发送adb logcat命令开始捕获日志
                _logMonitorProcess.StandardInput.WriteLine("adb shell logcat");
                _logMonitorProcess.StandardInput.Flush();

                // 跳过初始的缓冲区内容
                SkipInitialOutput(_logMonitorProcess, 10, 500);

                // 使用异步方式读取输出，提高响应性
                Task.Run(async () =>
                {
                    try
                    {
                        using (StreamReader reader = _logMonitorProcess.StandardOutput)
                        {
                            char[] buffer = new char[4096];
                            StringBuilder lineBuilder = new StringBuilder();

                            while (!token.IsCancellationRequested && _isLogMonitorRunning)
                            {
                                if (reader.EndOfStream || _logMonitorProcess.HasExited)
                                    break;

                                int charsRead = await reader.ReadAsync(buffer, 0, buffer.Length);
                                if (charsRead > 0)
                                {
                                    for (int i = 0; i < charsRead; i++)
                                    {
                                        char c = buffer[i];
                                        if (c == '\n')
                                        {
                                            string line = lineBuilder.ToString().Trim();
                                            if (!string.IsNullOrEmpty(line))
                                            {
                                                // 在UI线程中处理日志
                                                if (ShouldProcessLog(line))
                                                {
                                                    ProcessLogOutput(line, worker);
                                                }
                                            }
                                            lineBuilder.Clear();
                                        }
                                        else if (c != '\r')
                                        {
                                            lineBuilder.Append(c);
                                        }
                                    }
                                }

                                // 短暂延迟以减少CPU占用
                                await Task.Delay(10);
                            }

                            // 处理最后一行
                            string lastLine = lineBuilder.ToString().Trim();
                            if (!string.IsNullOrEmpty(lastLine) && ShouldProcessLog(lastLine))
                            {
                                ProcessLogOutput(lastLine, worker);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!token.IsCancellationRequested)
                        {
                            WriteToLogFile($"日志读取错误: {ex.Message}");
                        }
                    }
                }, token).Wait(token); // 等待任务完成或取消

                WriteToLogFile("日志监控结束");
            }
            catch (Exception ex)
            {
                if (!token.IsCancellationRequested)
                {
                    SafeUpdateTextBox(logTxt, $"日志监控错误: {ex.Message}");
                    WriteToLogFile($"日志监控错误: {ex.Message}");
                }
            }
            finally
            {
                lock (_processLock)
                {
                    // 安全停止进程
                    if (_logMonitorProcess != null && !_logMonitorProcess.HasExited)
                    {
                        SafeStopProcess(_logMonitorProcess);
                    }
                    _logMonitorProcess = null;
                    _isLogMonitorRunning = false;
                }
            }
        }


        /// <summary>
        /// 清空logcat缓冲区
        /// </summary>
        private void ClearLogcatBuffer()
        {
            try
            {
                using (Process clearProcess = new Process())
                {
                    clearProcess.StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        UseShellExecute = false,
                        CreateNoWindow = true,
                        WorkingDirectory = workingDirectory
                    };

                    clearProcess.Start();

                    // 构建清空命令（考虑设备序列号）
                    string clearCommand = BuildAdbCommand("adb logcat -c");
                    clearProcess.StandardInput.WriteLine(clearCommand);
                    clearProcess.StandardInput.Flush();

                    Thread.Sleep(200); // 等待清空命令完成

                    clearProcess.StandardInput.WriteLine("exit");
                    if (!clearProcess.WaitForExit(1000))
                    {
                        clearProcess.Kill();
                    }
                }

                SafeUpdateTextBox(comTxt, "日志缓存已清空");
                WriteToLogFile("日志缓存已清空");
            }
            catch (Exception ex)
            {
                SafeUpdateTextBox(comTxt, $"清空日志缓存失败: {ex.Message}");
                WriteToLogFile($"清空日志缓存失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 跳过初始输出行
        /// </summary>
        private void SkipInitialOutput(Process process, int linesToSkip, int waitMs)
        {
            try
            {
                Thread.Sleep(waitMs); // 等待进程稳定

                for (int i = 0; i < linesToSkip; i++)
                {
                    if (!process.StandardOutput.EndOfStream)
                    {
                        string line = process.StandardOutput.ReadLine();
                        SafeUpdateTextBox(logTxt, $"跳过的初始行 {i + 1}: {line}");
                        Debug.WriteLine($"跳过的初始行 {i + 1}: {line}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"跳过初始输出时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 安全停止进程
        /// </summary>
        private void SafeStopProcess(Process process)
        {
            try
            {
                if (process != null && !process.HasExited)
                {
                    // 先尝试正常退出
                    process.StandardInput.WriteLine("exit");

                    if (!process.WaitForExit(1000))
                    {
                        // 强制终止
                        process.Kill();
                        process.WaitForExit(500);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"停止进程时出错: {ex.Message}");
            }
        }

        private void PingWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                SafeUpdateTextBox(logTxt, $"日志监控异常结束: {e.Error.Message}");
                UpdateStatus("日志监控异常结束");
            }
            else if (e.Cancelled)
            {
                SafeUpdateTextBox(logTxt, "日志监控已取消");
                UpdateStatus("日志监控已取消");
            }
            else
            {
                SafeUpdateTextBox(logTxt, "日志监控正常结束");
                UpdateStatus("日志监控正常结束");
            }
        }

        /// <summary>
        /// 判断是否需要处理该日志行
        /// </summary>
        private bool ShouldProcessLog(string logLine)
        {
            return !string.IsNullOrEmpty(logLine) &&
                   (logLine.Contains("Loop took") || logLine.Contains("addr=") || logLine.Contains("val="));
        }

        /// <summary>
        /// 处理日志输出
        /// </summary>
        private void ProcessLogOutput(string output, BackgroundWorker worker)
        {
            try
            {
                // 调用日志数据管理器解析和存储
                var logcatbool = LogcatDataManager.ParseAndStoreRegisterLog(output);

                if (logcatbool)
                {
                    // 只有成功解析和存储的日志才更新UI
                    SafeUpdateTextBox(logTxt, output);
                    WriteToLogFile($"监控日志: {output}");
                }
                else
                {
                    // 可选：记录被过滤的日志（用于调试）
                    //Debug.WriteLine($"过滤的日志: {output}");
                }

                // 检查取消请求
                if (worker.CancellationPending)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                // 记录解析错误，但不中断日志监控
                SafeUpdateTextBox(logTxt, $"日志解析错误: {ex.Message}");
                WriteToLogFile($"日志解析错误: {ex.Message}");
                Debug.WriteLine($"ProcessLogOutput错误: {ex}");
            }
        }

        #endregion

        private void ADBForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                // 1. 停止所有ADB进程
                AdbProcessManager.KillAllAdbProcesses();

                // 取消操作
                tokenSource?.Cancel();

                // 强制清理
                ForceCleanup();

                // 停止后台工作器
                if (pingWorker != null)
                {
                    if (pingWorker.IsBusy)
                    {
                        pingWorker.CancelAsync();

                        // 短暂等待
                        for (int i = 0; i < 10 && pingWorker.IsBusy; i++)
                        {
                            Thread.Sleep(100);
                        }
                    }
                    pingWorker.Dispose();
                    pingWorker = null;
                }

                // 释放其他资源
                tokenSource?.Dispose();
                tokenSource = null;

                // 取消注册事件
                UnregisterAdbServiceEvents();

                WriteToLogFile("ADB工具已关闭，资源已释放");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"资源释放过程中出错: {ex.Message}");
            }
        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            UpdateStatus("正在启动ADB服务...");
            adbService.ExecuteAdbCommand("adb start-server", "启动ADB服务");
            // 首先设置设备监听端口
            string tcpipCommand = BuildAdbCommand("adb tcpip 5555");
            adbService.ExecuteAdbCommand(tcpipCommand, "设置TCP/IP模式");
        }

        private void btnStopServer_Click(object sender, EventArgs e)
        {
            UpdateStatus("正在停止ADB服务...");
            adbService.ExecuteAdbCommand("adb kill-server", "停止ADB服务");
        }

        private void btnListDevices_Click(object sender, EventArgs e)
        {
            UpdateStatus("正在列出已连接设备...");
            adbService.ExecuteAdbCommand("adb devices", "列出设备");
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtIpAddress.Text))
            {
                MessageBox.Show("请输入设备IP地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string ipAddress = txtIpAddress.Text.Trim();
            string port = string.IsNullOrEmpty(txtPort.Text) ? "5555" : txtPort.Text.Trim();

            UpdateStatus($"正在通过TCP/IP连接设备 {ipAddress}:{port}...");

            // 首先设置设备监听端口
            string tcpipCommand = BuildAdbCommand("adb tcpip 5555");
            adbService.ExecuteAdbCommand(tcpipCommand, "设置TCP/IP模式");

            // 然后连接设备
            string connectCommand = $"adb connect {ipAddress}:{port}";
            adbService.ExecuteAdbCommand(connectCommand, "TCP/IP连接设备");

          
            string shellCommand = $"adb shell";
            adbService.ExecuteAdbCommand(shellCommand, "连接设备 shell");
            
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtIpAddress.Text))
            {
                MessageBox.Show("请输入设备IP地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string ipAddress = txtIpAddress.Text.Trim();
            string port = string.IsNullOrEmpty(txtPort.Text) ? "5555" : txtPort.Text.Trim();

            UpdateStatus($"正在断开设备连接 {ipAddress}:{port}...");

            string disconnectCommand = $"adb disconnect {ipAddress}:{port}";
            adbService.ExecuteAdbCommand(disconnectCommand, "断开设备连接");
        }

        /// <summary>
        /// 重启ADB服务
        /// </summary>
        private void RestartAdbServer()
        {
            try
            {
                UpdateStatus("正在重启ADB服务...");

                // 先停止服务
                adbService.ExecuteAdbCommand("adb kill-server", "停止ADB服务");

                // 等待一下
                Thread.Sleep(1000);

                // 再启动服务
                adbService.ExecuteAdbCommand("adb start-server", "启动ADB服务");

                // 检查设备连接
                Thread.Sleep(2000);
                adbService.ExecuteAdbCommand("adb devices", "检查设备连接");

                // 首先设置设备监听端口
                string tcpipCommand = BuildAdbCommand("adb tcpip 5555");
                adbService.ExecuteAdbCommand(tcpipCommand, "设置TCP/IP模式");

                UpdateStatus("ADB服务重启完成");
            }
            catch (Exception ex)
            {
                SafeUpdateTextBox(comTxt, $"重启ADB服务失败: {ex.Message}");
                UpdateStatus("ADB服务重启失败");
            }
        }

        // 新增按钮点击事件
        private void btnRemount_Click(object sender, EventArgs e)
        {
            UpdateStatus("正在重新挂载系统分区...");
            string command = BuildAdbCommand("adb remount");
            adbService.ExecuteAdbCommand(command, "重新挂载系统分区");
        }

        private void btnReboot_Click(object sender, EventArgs e)
        {
            UpdateStatus("正在重启设备...");
            string command = BuildAdbCommand("adb reboot");
            adbService.ExecuteAdbCommand(command, "重启设备");
        }

        private void btnShell_Click(object sender, EventArgs e)
        {
            UpdateStatus("正在进入设备Shell...");
            string command = BuildAdbCommand("adb shell");
            adbService.ExecuteAdbCommand(command, "进入设备Shell");
        }

        private void btnPush_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openDialog = new OpenFileDialog())
            {
                openDialog.Title = "选择要推送的文件";
                if (openDialog.ShowDialog() == DialogResult.OK)
                {
                    string localFile = openDialog.FileName;
                    string remotePath = "/sdcard/" + Path.GetFileName(localFile);

                    UpdateStatus($"正在推送文件到设备: {remotePath}");
                    string command = BuildAdbCommand($"adb push \"{localFile}\" \"{remotePath}\"");
                    adbService.ExecuteAdbCommand(command, "推送文件到设备");
                }
            }
        }

        private void btnPull_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog saveDialog = new SaveFileDialog())
            {
                saveDialog.Title = "保存从设备拉取的文件";
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    string remoteFile = "/sdcard/"; // 这里可以根据需要修改默认路径
                    string localFile = saveDialog.FileName;

                    UpdateStatus($"正在从设备拉取文件: {remoteFile}");
                    string command = BuildAdbCommand($"adb pull \"{remoteFile}\" \"{localFile}\"");
                    adbService.ExecuteAdbCommand(command, "从设备拉取文件");
                }
            }
        }

      
       
    }
}